package com.lsy.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsy.response.Result;
import com.lsy.system.entity.User;
import com.lsy.system.mapper.UserMapper;
import com.lsy.system.service.AliOssService;
import com.lsy.system.service.LoginLogService;
import com.lsy.system.service.UserService;
import com.lsy.vo.UserVO;

import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lsy
 * @since 2022-02-12
 */
@RestController
@RequestMapping("/system/user")
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private AliOssService aliOssService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginLogService loginLogService;


    /**
     * 分页查询用户列表
     *
     * @return
     */
    @GetMapping("/findUserList")
    public Result findUserList(@RequestParam(required = true, defaultValue = "1") Integer current,
                               @RequestParam(required = true, defaultValue = "6") Integer size) {
        //对用户进行分页。泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current, size);
        //单表好用
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    /**
     * 根据用户条件进行分页查询
     *
     * @param current
     * @param size
     * @param userVO
     * @return
     */
    @PostMapping("/findUserPage")
    public Result findUserPage(@RequestParam(required = true, defaultValue = "1") Integer current,
                               @RequestParam(required = true, defaultValue = "6") Integer size,
                               @RequestBody UserVO userVO) {
        //对用户进行分页,泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current, size);
        //单表的时候其实这个方法是非常好用的
        QueryWrapper<User> wrapper = getWrapper(userVO);
        IPage<User> userPage = userService.findUserPage(page, wrapper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    /**
     * 封装查询条件
     *
     * @param userVO
     * @return
     */
    private QueryWrapper<User> getWrapper(UserVO userVO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userVO != null) {
            if (!StringUtils.isEmpty(userVO.getDepartmentId())) {
                queryWrapper.eq("department_id", userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())) {
                queryWrapper.eq("username", userVO.getUsername());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())) {
                queryWrapper.eq("email", userVO.getEmail());
            }
            if (!StringUtils.isEmpty(userVO.getSex())) {
                queryWrapper.eq("sex", userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())) {
                queryWrapper.eq("nickname", userVO.getNickname());
            }
        }
        return queryWrapper;
    }

    /*@ApiOperation("oss.上传文件")
    @PostMapping("/upload")
    public Result upload (MultipartFile file){
        String upload = aliOssService.upload(file);
        return Result.ok() .message(upload);
    }*/

    /**
     * 添加用户信息
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "添加用户", notes = "添加用户信息")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) {
        try {
            userService.addUser(user);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required = false) UserVO userVO) throws IOException {
        Page<User> page = new Page<>(1, 100);
        Page<User> userList = userService.findUserList(page, userVO);
        List<User> users = userList.getRecords();
        userService.exportUserExcel(response, users);
       /* List<User> users =userService.findUsers( userVO);
        userService.exportUserExcel(response,users);*/

    }

    @ApiOperation(value = "用户登入", notes = "接收参数用户名和密码,登入成功后,")
    @PostMapping("/login")
    public Result login(@RequestParam(value = "username", required = true) String username,
                        @RequestParam(value = "password", required = true) String password,
                        @RequestParam(value = "verifyCode", required = true) String verifyCode,
                        HttpServletRequest request) {
        System.out.println(username + password);
        /*System.out.println(verifyCode);
        if (!CaptchaUtil.ver(verifyCode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return Result.error().message("验证码不正确");
        }*/

        String token = userService.login(username, password);
//        loginLogService.add(request);
        //登录日志（SpringAop+反射)
        loginLogService.addLoginLog(request);
        return Result.ok().data("token", token);


    }

}

